package org.css.mobile.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.css.mobile.system.dao.CcsUserDetailInfoDao;
import org.css.mobile.system.domain.CcsUserDetailInfo;
import org.css.mobile.system.service.MobileUserService;
import org.css.mobile.system.vo.MobilePersonalInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 移动端用户服务实现类
 */
@Service
@Slf4j
public class MobileUserServiceImpl implements MobileUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CcsUserDetailInfoDao ccsUserDetailInfoDao;

    @Override
    public AjaxResult getUserInfo(Long userId) {
        // 查询用户基础信息
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        // 查询用户详细信息
        Optional<CcsUserDetailInfo> ccsUserDetailInfo = Optional.ofNullable(ccsUserDetailInfoDao.selectByUserId(sysUser.getUserId()));

        // 封装 VO
        MobilePersonalInfoVO mobilePersonalInfoVO = new MobilePersonalInfoVO();
        mobilePersonalInfoVO
                .setUserId(sysUser.getUserId())
                .setName(sysUser.getNickName())
                .setSex(sysUser.getSex())
                .setPhone(sysUser.getPhonenumber())
                .setEmail(sysUser.getEmail());

        ccsUserDetailInfo.ifPresent(bean -> {
                mobilePersonalInfoVO
                        .setAge(bean.getAge())
                        .setZjhm(bean.getIdentification())
                        .setZjType(bean.getIdentificationType());
                });

        return AjaxResult.success(mobilePersonalInfoVO);
    }

    @Override
    public AjaxResult update(MobilePersonalInfoVO dto) {
        // 封装用户
        SysUser sysUser = new SysUser();
        sysUser.setUserId(dto.getUserId());
        sysUser.setUserName(dto.getName());
        sysUser.setSex(dto.getSex());
        sysUser.setPhonenumber(dto.getPhone());
        sysUser.setEmail(dto.getEmail());
        // 更新用户
        int i = sysUserMapper.updateUser(sysUser);
        log.info("更新用户信息：{}", i);

        // 封装详细信息
        CcsUserDetailInfo ccsUserDetailInfo = new CcsUserDetailInfo();
        ccsUserDetailInfo.setUserId(dto.getUserId());
        ccsUserDetailInfo.setAge(dto.getAge());
        ccsUserDetailInfo.setIdentification(dto.getZjhm());
        ccsUserDetailInfo.setIdentificationType(dto.getZjType());
        // 是否存在详细信息
        if (ccsUserDetailInfoDao.selectByUserId(dto.getUserId()) == null) {
            ccsUserDetailInfoDao.save(ccsUserDetailInfo);
        } else {
            ccsUserDetailInfoDao.updateByUserId(ccsUserDetailInfo);
        }
        return AjaxResult.success("修改成功");
    }
}
